#lang r5rs
(define (count-pairs x)
  (if (not (pair? x))
      0
      (+ (count-pairs (car x))
         (count-pairs (cdr x))
         1)))
(define x (list 'a 'b 'c))
(define y (cons 'x (cons 'y '())))
(define z (cons 'x 'y))
(set-car! z y)
(set-cdr! z (cdr y))
(define a (cons 'a 'b))
(define b (cons 'a 'b))
(define c (cons 'a 'b))
(set-car! c b)
(set-cdr! c b)
(set-car! b a)
(set-cdr! b a)
(define ring (cons 'a 'b))
(set-car! ring ring)

(define (not-new-pairs? x stack)
  (if (null? stack)
      #f
      (or (eq? x (car stack)) (not-new-pairs? x (cdr stack)))))
(define (rrcount-pairs x)
  (define stack '())
  (define (rcount-pairs x)
    (cond ((not (pair? x))    0)
          ((not-new-pairs? x stack) (+ (rcount-pairs (car x)) (rcount-pairs (cdr x))))
          (else (begin (set! stack (cons x stack)) (+ (rcount-pairs (car x)) (rcount-pairs (cdr x)) 1)))))
  (rcount-pairs x))